import { defineStore } from 'pinia'
import { ref } from 'vue'
import { random } from 'lodash'
import type { QuickJump } from './types'

const useQuickJumpStore = defineStore(
  'quickJump',
  () => {
    const quickJumpList = ref<QuickJump[]>([
      {
        id: 0,
        url: 'https://www.bilibili.com/favicon.ico',
        title: '哔哩哔哩',
        target: 'https://www.bilibili.com/'
      },
      {
        id: 1,
        url: 'https://juejin.cn/favicon.ico',
        title: '稀土掘金',
        target: 'https://juejin.cn/'
      },
      {
        id: 2,
        url: 'https://github.com/favicon.ico',
        title: 'GitHub',
        target: 'https://www.github.com'
      }
    ])

    const deleteQuickJump = (data: QuickJump) => {
      const index = quickJumpList.value.findIndex(item => {
        if (
          item.url === data.url &&
          item.target === data.target &&
          item.title === data.title
        ) {
          return true
        }
      })
      quickJumpList.value.splice(index, 1)
    }

    const setQuickJump = (data: QuickJump) => {
      return new Promise(resolve => {
        quickJumpList.value.forEach(item => {
          if (item.id === data.id) {
            Object.assign(item, data)
          }
        })
        resolve(true)
      })
    }

    const addQuickJump = (data: QuickJump) => {
      return new Promise(resolve => {
        const copyData = JSON.parse(JSON.stringify(data))
        copyData.id = random(10000000, 99999999)
        quickJumpList.value.push(copyData)
        resolve(true)
      })
    }

    return { quickJumpList, deleteQuickJump, setQuickJump, addQuickJump }
  },
  {
    persist: {
      key: 'quick-jump-storage',
      storage: localStorage,
      paths: ['quickJumpList']
    }
  }
)

export default useQuickJumpStore
